package com.jason.platform.supervision.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.*;
import com.hzlj.supervision.changsha.R;
import com.jason.platform.supervision.BootApp;
import com.jason.platform.supervision.base.Constant;
import com.jason.platform.supervision.beans.LoginReq;
import com.jason.platform.supervision.beans.UserInfoBean;
import com.jason.platform.supervision.beans.VersionBean;
import com.jason.platform.supervision.beans.VersionResp;
import com.jason.platform.supervision.task.*;
import com.jason.platform.supervision.utils.SharedPreferencesUtils;
import com.jason.platform.supervision.widght.LoadingDialog;
import com.jason.platform.supervision.widght.TitleBar;
import org.kymjs.aframe.utils.SystemTool;

import java.io.File;

/**
 * @ClassName: LoginActivity
 * @Description: 登录
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015-7-26 13:54:05
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener,CompoundButton.OnCheckedChangeListener,TaskListener {

    private static final String TAG = LoginActivity.class.getSimpleName();

    private static final boolean isDebug = true;
    private MyHandler<LoginActivity> mHandler;

    private TitleBar mTitleBar;

    private EditText mAccountEditText;
    private EditText mPasswordEditText;
    private CheckBox mRemindPasswordCheckBox;
    private Button mLoginButton;

    private boolean mIsRemindPassword = false;
    private String mAccount;
    private String mPassword;

    private LoginReq mLoginReq;

    private RelativeLayout mHeaderLayout;
    private TextView mHeaderTitleTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        mHandler = new MyHandler<LoginActivity>(this);
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mTitleBar.bindActivity(this);
        mAccountEditText = (EditText) findViewById(R.id.login_account);
        mPasswordEditText = (EditText) findViewById(R.id.login_password);
        mRemindPasswordCheckBox = (CheckBox) findViewById(R.id.login_remind_password);
        mLoginButton = (Button) findViewById(R.id.login_login);
        mRemindPasswordCheckBox.setOnCheckedChangeListener(this);
        mLoginButton.setOnClickListener(this);
        mIsRemindPassword = SharedPreferencesUtils.getRemindPassword(this);
        mRemindPasswordCheckBox.setChecked(mIsRemindPassword);
        mRemindPasswordCheckBox.setVisibility(View.GONE);

        mLoginReq = SharedPreferencesUtils.getLoginInfo(this);
        if (mLoginReq != null){
            mAccountEditText.setText(mLoginReq.loginName);
//            mPasswordEditText.setText(mLoginReq.loginPwd);
        }

        mHeaderTitleTextView = (TextView) findViewById(R.id.login_header_title);
        mHeaderTitleTextView.setText(Html.fromHtml(getString(R.string.login_header_title)));

        mHeaderLayout = (RelativeLayout) findViewById(R.id.login_header_layout);
        updateWindowSoftState();
    }


    private void updateWindowSoftState(){
        final View decorView = this.getWindow().getDecorView();
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);
                int displayHight = rect.bottom - rect.top;
                int hight = decorView.getHeight();
                boolean visible = (double) displayHight / hight < 0.8;

                if (visible) {
                    System.out.println("软键盘打开了");
                    mHeaderLayout.setVisibility(View.GONE);
                } else {
                    System.out.println("软键盘关闭了");
                    mHeaderLayout.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    protected void initLoadingDialog() {
        super.initLoadingDialog();
        mLoadingDialog = new LoadingDialog(this);
        mLoadingDialog.setIsOut(false);
        mLoadingDialog.setMessage("登录中...");
    }

    @Override
    protected void initData() {
        super.initData();
        //检查版本升级
        if (BootApp.NEW_VERSION_FLAG){
            if (SharedPreferencesUtils.getLoginInfo(this) != null){
                startActivity(new Intent(this,HomeActivity.class));
                finish();
                return;
            }
        }
        if(SystemTool.checkNet(BootApp.getAppContext())){
            mLoadingDialog.setMessage("检查版本更新中...");
            mLoadingDialog.show();
            QueryVersionTask task = new QueryVersionTask(this);
            task.type = Constant.Version.GET_VERSION;
            task.execute();
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.login_login){
            mAccount = mAccountEditText.getText().toString();
            mPassword = mPasswordEditText.getText().toString();
            if (mLoadingDialog != null){
                mLoadingDialog.setMessage("登录中...");
                mLoadingDialog.show();
            }
            LoginTask loginTask = new LoginTask(this);
            loginTask.type = Constant.Datb.LOGIN;
            loginTask.mParams.put("loginName", mAccount);
            loginTask.mParams.put("loginPwd", mPassword);
            loginTask.execute();
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        mIsRemindPassword = isChecked;
        SharedPreferencesUtils.setRemindPassword(this,mIsRemindPassword);
    }

    @Override
    void handleMessage(BaseActivity activity, Message msg) {
        Task task = (Task) msg.obj;
        if (task.type == Constant.Datb.LOGIN){
            if (mLoadingDialog != null){
                mLoadingDialog.dismiss();
            }
            Toast.makeText(this,task.rspDesc,Toast.LENGTH_SHORT).show();
            if (task.isSuccess){
                UserInfoBean userInfoBean = (UserInfoBean)task.resData;
                SharedPreferencesUtils.setLoginInfo(LoginActivity.this,new LoginReq(mAccount,mPassword));
                if (userInfoBean != null){
                    BootApp.USER_ORANGE_ID = userInfoBean.getOrganId();
                    BootApp.USER_INFO = userInfoBean;
                    SharedPreferencesUtils.setUserInfoBean(LoginActivity.this, userInfoBean);
                    SharedPreferencesUtils.setOrganId(LoginActivity.this, userInfoBean.getOrganId());
                }
                startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                finish();
            }
        } else if (task.type == Constant.Version.GET_VERSION){
            if (mLoadingDialog != null){
                mLoadingDialog.dismiss();
            }
            if (task.isSuccess){
                VersionResp resp = (VersionResp) task.resData;
                VersionBean bean = resp.getValues().get(0);
                //下载版本
                checkVersionDialog(bean);
            }
        }
    }

    private Handler mDownloadHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mLoadingDialog != null){
                mLoadingDialog.dismiss();
            }
            if (msg.what == 0){
                downloadFinish((String)msg.obj);
            }
        }
    };

    private void downloadFinish(String saveFileName){
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        startActivity(i);
    }

    @Override
    public void onTaskResult(Task task) {
        Message msg = new Message();
        msg.obj = task;
        mHandler.sendMessage(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoadingDialog != null){
            mLoadingDialog.dismiss();
        }
    }

    private void checkVersionDialog(final VersionBean bean){
        new AlertDialog.Builder(this).setTitle("更新").setMessage("是否进行应用更新？")
                .setCancelable(true)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mLoadingDialog.setMessage("请稍等，正在下载中...");
                        mLoadingDialog.show();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                DownloadTask logic = new DownloadTask(bean,mDownloadHandler);
                                logic.start();
                            }
                        }).start();

                    }

                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();

            }

        }).setOnKeyListener(new DialogInterface.OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        }).setCancelable(false).create().show();
    }
}
